package com.wind.cloud.common.util;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 事务同步
 *
 * @author wind.
 */
public class TransactionSynchronization {

    private static PlatformTransactionManager transactionManager = null;

    /**
     * 事务提交成功后回调，没有事务直接回调
     *
     * @param cb 回调
     */
    public static void afterCommit(final Callback cb) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    cb.execute();
                }
            });
        } else {
            // 没有事务直接回调
            cb.execute();
        }
    }

    /**
     * 事务回滚后回调（如果回调逻辑要保证事务，建议新线程执行），没有事务抛出异常
     *
     * @param cb 回调
     */
    public static void afterRollback(final Callback cb) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCompletion(int i) {
                    if (i == org.springframework.transaction.support.TransactionSynchronization.STATUS_ROLLED_BACK
                            || i == org.springframework.transaction.support.TransactionSynchronization.STATUS_UNKNOWN) {
                        cb.execute();
                    }
                }
            });
        } else {
            // 没有事务
            throw new IllegalStateException("当前没有事务");
        }
    }

    /**
     * 事务提交成功后回调，没有事务直接回调（新事务执行）
     *
     * @param cb 回调
     */
    public static void afterCommitInNewTransaction(final Callback cb) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    doInNewTransaction(cb);
                }
            });
        } else {
            // 没有事务直接回调
            cb.execute();
        }
    }

    public static void doInNewTransaction(final Callback cb) {
        // 开启新事务
        TransactionTemplate transactionTemplate = new TransactionTemplate(getTransactionManager());
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                cb.execute();
            }
        });
    }

    private static PlatformTransactionManager getTransactionManager() {
        if (transactionManager == null) {
            transactionManager = SpringUtils.getBean(PlatformTransactionManager.class);
        }
        return transactionManager;
    }

    public interface Callback {
        void execute();
    }
}
